import React from 'react'
import NavHeader from '@/components/NavHeader'
import styles from './index.module.css'
import { getCurrentCity } from '@/utils/index'
import { getNewsApi } from '@/api/home'
import { BASE_URL } from '@/utils/url'
import { Carousel, Flex, Grid, WingBlank } from 'antd-mobile'

export default class News extends React.Component {
  state = {
    cityId: '',
    news: []
  }

  componentDidMount () {
    this.getcityMessage()
  }
  componentDidUpdate (prevProps, prevState) {
    if (prevState.cityId !== this.state.cityId) {
      this.getNews()
    }
  }

  getcityMessage = async () => {
    let { value } = await getCurrentCity()
    console.log(value)
    this.setState({
      cityId: value
    })
  }

  // 获取资讯的数据
  async getNews () {
    const res = await getNewsApi(this.state.cityId)
    console.log('打印资讯', res)
    this.setState(() => {
      return {
        news: res.data.body
      }
    })
  }

  // 资讯UI渲染
  renderNews () {
    return this.state.news.map(item => (
      <div className={styles.newsitem} key={item.id}>
        <div className={styles.imgwrap}>
          <img className={styles.img} src={BASE_URL + item.imgSrc} alt='' />
        </div>
        <Flex className={styles.content} direction='column' justify='between'>
          <h3 className={styles.title}>{item.title}</h3>
          <Flex className={styles.info} justify='between'>
            <span>{item.from}</span>
            <span>{item.date}</span>
          </Flex>
        </Flex>
      </div>
    ))
  }
  render () {
    const { history } = this.props
    return (
      <div className={styles.root}>
        <NavHeader onLeftClick={() => history.go(-1)}>本地资讯</NavHeader>
        <div className={styles.news}>{this.renderNews()}</div>
      </div>
    )
  }
}
